<?php

namespace app\stock\controller;

use think\Controller;
/*
公海
*/

class Highsea extends Controller
{
    // 用户模型
    protected $BusinessModel;
    // 客户领取模型
    protected $ReceiveModel;
    private $AdminModel;
    protected $relationSearch = true;
    public function _initialize()
    {
        // 继承父类
        parent::_initialize();
        $this->BusinessModel = model('Business.Business');
        $this->AdminModel = model('Admin');
        $this->ReceiveModel = model('Business.Receive');
    }
    /**
     * 公海首页
     */
    public function index()
    {
        $list = $this->BusinessModel->with('scource')->whereNull('adminid')->order('id', 'desc')->select();
        $this->success("", "", $list);
    }
    /**
     * 详情
     */
    public function info()
    {
        $id = $this->request->param('id', 0, 'trim');
        $info = $this->BusinessModel->with('scource')->find($id);
        if (!$info) {
            $this->error("用户不存在");
        }
        $this->success("", "", $info);
    }
    /**
     * 删除
     */
    public function del()
    {
        $id = $this->request->param('id', 0, 'trim');
        $info = $this->BusinessModel->find($id);
        if (!$info) {
            $this->error("用户不存在");
        }
        $result = $this->BusinessModel->destroy($id);
        if ($result == false) {
            $this->error("删除失败");
        }
        $this->success("删除成功");
    }
    // 领取
    public function apply()
    {
        $busid = $this->request->param('busid', 0, 'trim');
        $adminid = $this->request->param('adminid', 0, 'trim');
        $status = $this->request->param('status', '', 'trim');

        $businessinfo = $this->BusinessModel->find($busid);

        if (!$businessinfo) {
            $this->error('客户不存在');
        }

        $admininfo = $this->AdminModel->find($adminid);

        if (!$admininfo) {
            $this->error('管理员不存在');
        }

        $this->BusinessModel->startTrans();
        $this->ReceiveModel->startTrans();

        $ReceiveData = [
            'applyid' => $adminid,
            'status' => $status,
            'busid' => $busid,
        ];
        $ReceiveStatus = $this->ReceiveModel->validate('common/Business/Receive')->save($ReceiveData);

        if ($ReceiveStatus === false) {
            $this->error($this->ReceiveModel->getError());
        }

        $BusinessStatus = $this->BusinessModel->where('id', $busid)->update(['adminid' => $adminid]);

        if ($BusinessStatus === false) {
            $this->ReceiveModel->rollback();
            $this->error('操作失败');
        }
            $this->ReceiveModel->commit();
            $this->BusinessModel->commit();
            $this->success('操作成功');
    }

    // 获取管理员列表
    public function admin()
    {
        $data = $this->AdminModel->select();

        $this->success('', '', $data);
    }
}
